package com.app.micaihu.view.user.userinfo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.NoDoubleClickListener;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.MaxByteLengthEditText;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;


/**
 * 修改昵称页面
 * Created by Guo on 2016/12/7.
 */

public class EditorUserInfoActivity extends BaseOldActivity {


    private String title;
    private LinearLayout llNickName;
    private MaxByteLengthEditText etNickName;
    private ImageView ivCancel;
    private RelativeLayout rlSignature;
    private MaxByteLengthEditText etSignautre;
    private String type = "1";  //1 是昵称,2 是签名
    private TextView tvSignatureCount;
    private static final int SIGNATURE_MAX_LENGTH = 40;
    private static final int NICKNAME_MAX_LENGTH = 16;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        setTitle(title);

        addContentView(R.layout.activity_editor_userinfo);
        //初始化页面
        initView();
    }

    private void initView() {
        setTitleRightText(AppApplication.getInstance().getString(R.string.common_done))
                .setOnClickListener(onClickListener);
        llNickName = (LinearLayout) findViewById(R.id.ll_nickname);
        etNickName = (MaxByteLengthEditText) findViewById(R.id.et_content_nickname);
        ivCancel = (ImageView) findViewById(R.id.iv_cancel);
        rlSignature = (RelativeLayout) findViewById(R.id.rl_signature);
        etSignautre = (MaxByteLengthEditText) findViewById(R.id.et_content_signature);
        tvSignatureCount = (TextView) findViewById(R.id.tv_count);


        etNickName.setMaxByteLength(NICKNAME_MAX_LENGTH);
        etNickName.addTextChangedListener(textWatcherListener);

        etSignautre.setMaxByteLength(SIGNATURE_MAX_LENGTH);
        tvSignatureCount.setText((SIGNATURE_MAX_LENGTH / 2) + "");
        etSignautre.addTextChangedListener(textWatcherListener);


        ivCancel.setOnClickListener(onClickListener);

        if (isNickName()) {
            llNickName.setVisibility(View.VISIBLE);
            rlSignature.setVisibility(View.GONE);
            if (UserInforManager.getInstance().isLogin()) {
                etNickName.setText(UserInforManager.getInstance().getUserInfor().getNickName());
                if (etNickName.getCurrentByteLen() <= NICKNAME_MAX_LENGTH) {
                    etNickName.setSelection(etNickName.getText().toString().trim().length());

                }
            }
        } else {
            llNickName.setVisibility(View.GONE);
            rlSignature.setVisibility(View.VISIBLE);
            if (UserInforManager.getInstance().isLogin()) {
                etSignautre.setText(UserInforManager.getInstance().getUserInfor().getSignature());
                if (etSignautre.getCurrentByteLen() <= SIGNATURE_MAX_LENGTH) {
                    etSignautre.setSelection(etSignautre.getText().toString().trim().length());
                }
            }
        }


        etSignautre.setOnEditorActionListener(enterEditorActionListener);
        etNickName.setOnEditorActionListener(enterEditorActionListener);


    }

    TextView.OnEditorActionListener enterEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
        }
    };


    TextWatcher textWatcherListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etSignautre.getVisibility() == View.VISIBLE) {
                int byteLen = etSignautre.getCurrentByteLen() / 2;
                tvSignatureCount.setText(((SIGNATURE_MAX_LENGTH / 2) - byteLen) + "");

            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private boolean isNickName() {
        if (TextUtils.equals("1", type)) {
            return true;
        } else {
            return false;
        }

    }

    NoDoubleClickListener onClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            if (v == null) return;
            switch (v.getId()) {
                case R.id.page_head_function_text:
                    if (!UserInforManager.getInstance().isLogin()) {
                        return;
                    }
                    if (isNickName()) {//编辑昵称的
                        submitNickName();
                    } else {
                        submitSignature();
                    }
                    break;
                case R.id.iv_cancel:
                    if (etNickName != null) {
                        etNickName.setText("");
                    }
                    break;
            }
        }


    };

    private void submitSignature() {

        final String signature = etSignautre.getText().toString().trim();

        if (TextUtils.isEmpty(signature) && signature.length() > 30) {
            ToastUtils.makeText(getResources().getString(R.string.user_signature_tolong));
            return;
        }


        ParamMap params = new ParamMap();
        params.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        params.putEncode("signature", signature);
        HttpUtils.ParmsMapMD5(params);

        addPostRequest(URIContant.EDIT_SIGNATURE, new TypeToken<DataBean>() {
        }.getType(), params, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                DialogUtils.getInstance().showProgressDialog(EditorUserInfoActivity.this, "正在提交");
            }

            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                DialogUtils.getInstance().dismissProgressDialog();
            }

            @Override
            public void onSuccess(DataBean response) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (!response.noError()) {
                    ToastUtils.makeText(response.getMsg());
                } else {
                    ToastUtils.makeText("修改成功");
                    UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
                    userInfor.setSignature(signature);
                    UserInforManager.getInstance().saveUserInfor(userInfor);
                    onBackPressed();
                }
            }
        });
    }

    private void submitNickName() {

        String editNickName = etNickName.getText().toString().trim();

        //检查昵称的合法性
        boolean match = StringUtils.checkNickName(editNickName);
        if (!TextUtils.isEmpty(editNickName) && match) {//不相等,去发送请求
            commitNickName(editNickName);
        } else if (TextUtils.isEmpty(editNickName)) {
            ToastUtils.makeText(getResources().getString(R.string.user_nickname_noempty));
        } else if (!match) {
            ToastUtils.makeText(getResources().getString(R.string.user_nickname_error));
        }


    }

    private void commitNickName(final String editNickName) {


        ParamMap params = new ParamMap();

        params.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        params.putEncode("nickname", editNickName);
        HttpUtils.ParmsMapMD5(params);

        addPostRequest(URIContant.EDIT_NICKNAME, new TypeToken<DataBean>() {
        }.getType(), params, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                DialogUtils.getInstance().showProgressDialog(EditorUserInfoActivity.this, "正在提交");
            }

            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                DialogUtils.getInstance().dismissProgressDialog();
            }

            @Override
            public void onSuccess(DataBean response) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (!response.noError()) {
                    ToastUtils.makeText(response.getMsg());
                } else {

                    ToastUtils.makeText("修改成功");
                    UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
                    userInfor.setNickName(editNickName);
                    UserInforManager.getInstance().saveUserInfor(userInfor);
                    onBackPressed();
                }
            }
        });


    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            title = intent.getStringExtra(Config.Extra.PARAMETER1);
            type = intent.getStringExtra(Config.Extra.PARAMETER2);
        }

    }
}
